/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.j2ee.earproject;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.queries.SourceForBinaryQuery;
import org.netbeans.api.java.queries.SourceForBinaryQuery.Result;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation;
import org.netbeans.spi.project.SubprojectProvider;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.URLMapper;

/**
 *
 */
public class SourceForBinaryQueryImpl implements SourceForBinaryQueryImplementation {

    private final Map<String, SourceForBinaryQuery.Result> cache = new HashMap<String, SourceForBinaryQuery.Result>();

    private EarProject p;

    public SourceForBinaryQueryImpl(EarProject p) {
        this.p = p;
    }

    @Override
    public Result findSourceRoots(URL binaryRoot) {
        if (FileUtil.getArchiveFile(binaryRoot) != null) {
            binaryRoot = FileUtil.getArchiveFile(binaryRoot);
        }
        SourceForBinaryQuery.Result res = cache.get(binaryRoot.toExternalForm());
        if (res != null) {
            return res;
        }

        FileObject fo = URLMapper.findFileObject(binaryRoot);
        if (fo == null || fo.isFolder()) {
            return null;
        }

        String buildDir = p.evaluator().evaluate("${build.dir}/lib");
        if (buildDir == null) {
            return null;
        }
        FileObject libRoot = p.getAntProjectHelper().resolveFileObject(buildDir);
        if (libRoot == null) {
            return null;
        }
        if (!fo.getParent().equals(libRoot)) {
            return null;
        }
        String libFile = fo.getNameExt();

        for (Project subProject : p.getLookup().lookup(SubprojectProvider.class).getSubprojects()) {
            SourceGroup sgp[] = ProjectUtils.getSources(subProject).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
            if (sgp.length == 0) {
                continue;
            }
            ClassPath cp = ClassPath.getClassPath(sgp[0].getRootFolder(), ClassPath.COMPILE);
            if (cp == null) {
                continue;
            }
            for (ClassPath.Entry entry : cp.entries()) {
                URL u = entry.getURL();
                if (FileUtil.getArchiveFile(u) != null) {
                    u = FileUtil.getArchiveFile(u);
                }
                // #213372:
                if (u.toExternalForm().equals(binaryRoot.toExternalForm())) {
                    continue;
                }
                FileObject cpItem = URLMapper.findFileObject(u);
                if (cpItem == null || cpItem.isFolder()) {
                    continue;
                }
                if (cpItem.getNameExt().equals(libFile)) {
                    res = SourceForBinaryQuery.findSourceRoots(entry.getURL());
                    if (res != null) {
                        cache.put(binaryRoot.toExternalForm(), res);
                        return res;
                    }
                }
            }
        }

        return null;
    }

}
